﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LMKJ.Classes;
using System.Text.RegularExpressions;

namespace LMKJ
{
    public partial class additem : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void addBtn_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                Item i = new Item();
                i.Item_name = itemNameTbx.Text;
                i.Description = descriptionTbx.Text;
                string price = dollarsTbx.Text + "." + centsTbx.Text;
                i.Price = Convert.ToDouble(price);

                int success = DatabaseManager.CreateItem(i);

                if (success == 1)
                {
                    string jsPopup = "<script type='text/javascript'>" +
                        "alert('Successfully Created Item!');" +
                        "window.location.href = 'searchitems.aspx';" +
                        "</script>";
                    ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", jsPopup);
                }
            }
        }

        protected void cancelBtn_Click(object sender, EventArgs e)
        {
            Response.Redirect("searchitems.aspx");
        }

        protected void fieldsValidator_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (String.IsNullOrEmpty(itemNameTbx.Text.Trim())
                || String.IsNullOrEmpty(dollarsTbx.Text.Trim()))
            {
                args.IsValid = false;
            }
            else
            {
                args.IsValid = true;
            }
        }

        protected void priceValidator_ServerValidate(object source, ServerValidateEventArgs args)
        {
            Regex NumberOnly = new Regex("\\d+$");

            if (NumberOnly.IsMatch(dollarsTbx.Text) && NumberOnly.IsMatch(centsTbx.Text))
            {
                args.IsValid = true;
            }
            else
            {
                args.IsValid = false;
            }
        }

        protected void itemValidator_ServerValidate(object source, ServerValidateEventArgs args)
        {
            bool itemValid = DatabaseManager.CheckItemValidity(itemNameTbx.Text.Trim());

            if (itemValid)
            {
                args.IsValid = true;
            }
            else
            {
                args.IsValid = false;
            }
        }
    }
}